package learnjava.concur.chapter123;


import java.util.Hashtable;
import java.util.Map;

public class GuardedObjectTest{

    public static void main(String[] args){

        GuardedObject go = new GuardedObject();

        new Thread(()->{
            System.out.println(go.getResult(3*1000));
        },"receiver").start();

        new Thread(()->{
            try {
                Thread.sleep(2*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            go.setResult("wqngc");
        },"sender").start();
    }
}


class Mailboxes{
    private Map<Integer, GuardedObject> boxes = new Hashtable<>();
}



class GuardedObject {

    private int id;
    private Object result;

    public Object getResult(){
        synchronized (this){
            while (result==null){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return result;
        }
    }

    /**
     * 带时限的接收
     * join的原理
     * @param timeout
     * @return
     */
    public Object getResult(long timeout){
        synchronized (this){
            //开始时间
            long begin = System.currentTimeMillis();
            //剩余等待的总时间
            long leftTime = timeout;
            while (leftTime>0&&result==null){
                try {
                    //wait只对获取锁的线程有效
                    this.wait(leftTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                leftTime -= System.currentTimeMillis()-begin;
            }
            return result;
        }
    }

    public void setResult(Object o){
        synchronized (this){
            result = o;
            this.notifyAll();
        }
    }
}
